import Api from '../service/Api';
import ChoicePage from './news_mass_choice';
import {emojiArr} from '../common/Emoji';
import { emoImgToRect, addFileListener, renderFileDiv, stringGetFileTitle, formatType, allowEvent, sendTextFmt } from '../common/Function';
import ChatManager from '../component/ChatManager';

const userInfo = JSON.parse(localStorage.getItem('yxtUser'));

export function qunfaPage() {
  const {User_ID, SessionID} = userInfo;

  Api.get('/BasePlate/Interface/IInterfaceJson.asmx/MsgBatch_GetList', {
    User_ID,
    SessionID,
    PageIndex: 0,
    PageSize: 10
  }).then(resp => {
    console.log(resp);

    if (resp.Goodo && resp.Goodo.R) {
      const data = resp.Goodo.R;
      console.log(data)
      const tpl = `
        <div class="top">
          <p>群发</p>
        </div>
        <div class="mass">
          <ul>
            ${data.map(item => {
              return `
                <li>
                  <h1>${item.SendDate}</h1>
                  <div>
                    <p><span>${item.ReceiveUserNames.split(',').length}位收件人</span></p>
                    <p class="names">${item.ReceiveUserNames}</p>
                    <div><span>内容： </span>${formatType(item.MsgType, item.MsgContent)}</div>
                    <a data-ids="${item.ReceiveUserIDs}" data-names="${item.ReceiveUserNames}" class="agin_send_btn">再发一条</a>
                  </div>
                </li>
              `
            }).join('')}

          </ul>
          <a class="news_ma" href="###" role="button">新建群发</a>
        </div>
      `;
      $(".right").html(tpl);

      $(".right a.news_ma").click(() => {
        ChoicePage.render_qunfa();
      })
      $(".right a.agin_send_btn").click(function(){
        const ids = $(this).data('ids').split(',');
        const names = $(this).data('names').split(',');
        qunfaSendPage({ids, names, back: 1});
      })

    } else {
      const tpl = `
        <div class="top">
          <p>群发</p>
        </div>
        <div class="mass">
          <a class="news_ma" href="###" role="button">确认</a>
        </div>
      `;
      $(".right").html(tpl);

      $(".right a.news_ma").click(() => {
        ChoicePage.render_qunfa();
      })
    }
  })
}


export function qunfaSendPage({ids, names, back}) {
  const {SessionID, UserName, User_ID, Unit_ID} = JSON.parse(localStorage.getItem('yxtUser'));
  window.fileArr = [];
  const tpl = `
    <div class="top">
      <p>群发消息</p>
    <a class="qfSend_back_btn"><img src="img/news_public/news_sys.png"/></a>
    </div>
    <div class="discussion mass_s">
      <div class="main discu">
        <span>您将群发给<b>${ids.length}</b>位联系人；</span>
        <p>${names.join('；')}</p>
      </div>
      <div class="cursor_area" style="border-bottom: none;" ></div>
      <form class="news_mass_s kind_main">
        <a class="emoji"><img src="img/news_public/file_1.png"/></a>
        <label id="files"><img src="img/news_public/file_2.png"/></label>
        <div class="emoji_div"><ul></ul></div>
        <textarea id="editor_id2" name="content"></textarea>
        <a class="send-message" role="button">发送(s)<img src="img/news_public/anliu_1.png"/></a>
        <ul class="send_way">
            <li><img src="img/news_public/anliu_2.png"/><span>按Enter键发送消息</span></li>
            <li><img src="img/news_public/anliu_3.png"/><span>按Ctrl+Enter键发送消息</span></li>
        </ul>
      </form>
    </div>
  `;

  $(".right").html(tpl);
  $("a.qfSend_back_btn").click(()=>{
    switch (back) {
      case 1:
        qunfaPage();
        break;
      default:
        ChoicePage.render_qunfa();
    }
  })

  var K = window.KindEditor;
  window.sendMode = 1; // 发送的模式 0 -> entry发送 1 -> ctrl + endtry发送
  var editor = K.create('#editor_id2', {
    width: '1300px',
    newlineTag: 'br',
    //	items:'',
    display: 'block',
    height: '160px',
    resize: 'none',
    outline: 'none',
    paddingLeft: '8px',
    border: '0px #000000 solid',
    margin: '20px 0 0 25px',
    fontSize: '24px',
    lineHeight: '40px',
    color: '#333333',
    cssPath: 'css/do_boly.css',
    allowFileUpload: 'ture',
    resizeType: 1,
    htmlTags: {
      'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': [
        'align', 'style'
      ],
      img: [
        'src', 'width'
      ],
      div: [
        'disabled', 'class'
      ],
      p: ['title'],
      br: []
    },
    afterFocus: function() {
      // 隐藏表情选择面板
      $(".emoji_div").find('ul').empty();
      $(".emoji_div").css("display", "none");
      $flag = 1;
    },
    pasteType: 1 //粘贴 没格式
    //		allowPreviewEmoticons : false,
    //		allowImageRemote:true,  网络图片
    //		allowImageUpload : true, 本地图片开启
    //		afterBlur:function(){this.sync(); },  失去焦点 将 kindeditor的值同步给textarea
    //		items : [ 'removeformat', '|', 'image' ]
  });
  //    KindEditor.ready(function(K) {
  //        K.create('#editor_id');
  //    })
  K.sync('#editor_id2');
  var main = $('.discussion .main.discu'); ///盒子移动
  var ent = $('.kind_main').find('iframe').contents().find('body');
  var ifra = $('.kind_main').find('iframe');
  $('.cursor_area').mousedown(function(event) {
    $('body').css('user-select', 'none');
    $('.ke-edit-iframe').css('display', 'none');

    var e = event || window.event;
    var a = main.height();

    var b = ent.height()
    $('.discussion').mousemove(function(event) {
      var f = event || window.event;
      //					ent.attr({'display':'none'});
      //					$('.ke-container.ke-container-default').attr({'display':'none'});
      //					$('.ke-edit-iframe').attr({'display':'none'});
      //					K.create('#editor_id',{ display:'none'})
      var sum = a + f.pageY - e.pageY;
      //					var sum_iframe=b+e.pageY-f.pageY;
      var sum_iframe = 838 - sum;
      if (sum_iframe > 150) {
        main.height(sum);
        ent.height(sum_iframe);
        ifra.height(sum_iframe);
        //					ifra.parent().height(sum_iframe);
        ifra.parent().parent().height(sum_iframe);
      }
    });
  })
  $('.discussion').mouseup(function(event) {
    $('.discussion').unbind('mousemove');
    $('.ke-edit-iframe').css('display', 'block');

  });
  ent.mouseup(function(event) {
    $('.discussion').unbind('mousemove');
    ent.attr({'display': 'block'});
    //						ent.unbind('mousemove');
  });

  //添加表情
  var $flag = 1; // 标记
  $(".emoji").click(function(e) { //添加表情
    e.stopPropagation();
    if ($flag) {
      $(".emoji_div").css("display", "block");
      $flag = 0;
      var htmlobj = $.ajax({url: 'js/emoji(0).txt', async: false});
      var temp = htmlobj.responseText;
      var b = JSON.parse(temp); //(对象
      for (var i = 0; i < b.length; i++) { //表情赋值
        $(".emoji_div").find("ul").append('<li class="emochoice"><img class="emochoice" data-id="' + b[i].key + '" src="img/Emoticon/' + b[i].value + '"/></li>');
      }
      $(".emoji_div").find("ul").find("img").click(function(e) { //点击表情图标
        var a = $(this).attr("src");
        //							editor.html(editor.html()+ $(this)[0].outerHTML);
        editor.insertHtml($(this)[0].outerHTML);
        $(".emoji_div").find('ul').empty();;
        $(".emoji_div").css("display", "none");
        $flag = 1;
  //          e.stopPropogation();

      }); //双击取消


    } else {
      $(".emoji_div").find('ul').empty();
      $(".emoji_div").css("display", "none");
      $flag = 1;
    }

  });

  var fl=0;
  $(".right .discussion .send-message img").click(function(e){//选择发送方式弹框
      e.stopPropagation();
      if(fl==0){$(".right .discussion .send_way").css({'display':'block'});fl=1;}
      else{$(".right .discussion .send_way").css({'display':'none'});fl=0;}
  });
  $(".right .discussion .send_way li").click(function(){//选择发送方式
    $(".right .discussion .send_way").find("img").attr({"src":"img/news_public/anliu_3.png"});
    $(this).find("img").attr({"src":"img/news_public/anliu_2.png"});
    var img_name=$(".right .discussion .send_way li").eq(0).find("img").attr("src");
    if(img_name=="img/news_public/anliu_2.png"){window.sendMode = 0;}else{window.sendMode = 1;}
  })

  // 点击非emoji选择面板隐藏事件
  // $(".right").unbind('click');
  $(".right").on('click', function(e) {
    // 遍历点击传递路径，找是否有emoji_div
    try {
      e.path.forEach(item => {
        if (item.className == 'emoji_div') {
          throw new Error(`find emoji_div`)
        }
      })
    } catch (e) {
      $(".emoji_div").find('ul').empty();
      $(".emoji_div").css("display", "none");
      $flag = 1;
    }
    return true;
  })

  // 发送事件处理
  let sendWay = () => {
      editor.sync();
      let files;
      let content = editor.html();
      console.log(`content--------------------------`);
      console.log(content);
      let arr =stringGetFileTitle(content);
      content = arr[0];
      files = arr[1];
      content = emoImgToRect(content); // 转换emoji图片为 ‘[emoji]’
      console.log(`contentAfter--------------------------`);
      console.log(content);
      console.log(`files-------------------`);
      console.log(files);
			console.log(content.length)
      if (content.length > 506) { // 若文本长度过长跳出发送
        return layer.msg('文本长度过长~')
      }
       if (content.length ==0) { // 若文本长度过长跳出发送
        return layer.msg('文本为空~')
      }
      layer.msg(`发送中~`, {time:0});
      qunfa_mixSend(ids, names, sendTextFmt(content), files)
      .then(resp => {
        if (resp.length == 1) {
            layer.msg(resp[0])
        } else {
            layer.msg(resp[0], {time: 1000}, function() {
              layer.msg(resp[1])
            })
        }
        ChatManager.pollMessage();
        editor.html('');
        qunfaPage();
      })
  }

  // 发送事件绑定
  $(".right .send-message").click(sendWay);

  ent.keydown(function(e) {
    if (e.keyCode == 13 && !e.ctrlKey) {  // entry 事件绑定
      if (window.sendMode) { // sendMode 为 1 是ctrl + entry发送
        // editor.insertHtml('<br/>'); // 在此entry下对文本作回车处理
      } else { // sendMode 为 0 是entry发送
        sendWay()
      }
    }
  })
  K.ctrl(ent[0], 13, function(e) { // ctrl + entry 事件绑定
    if (window.sendMode) { // sendMode 为 1 是ctrl + entry发送
      sendWay()
    } else { // sendMode 为 0 是entry发送
      editor.insertHtml('<br />'); // 在此entry下对文本作回车处理
    }
  });

  // 读取文件事件处理
  addFileListener('#files', data => {
    allowEvent();
    layer.msg(`发送中~`, {time: 0});
    qunfa_mixSend(ids, names, null, [data.fileName], {
      up: (percent) => {console.log(`up: ${percent}`)},
      down: (percent) => {console.log(`down: ${percent}`)}
    })
    .then(resp => {
      if (resp.length == 1) {
          layer.msg(resp[0])
      } else {
          layer.msg(resp[0], {time: 1000}, function() {
            layer.msg(resp[1])
          })
      }
      ChatManager.pollMessage();
      editor.html('');
      qunfaPage();
    })

  })

}

function qunfa_mixSend(ids, names, content, files, cbs = {}) {
  let up = cbs.up;
  let down = cbs.down;
//const {SessionID, UserName, User_ID, Unit_ID} = JSON.parse(Cookies.get('yxtUser'));
  const {SessionID, UserName, User_ID, Unit_ID} = JSON.parse(localStorage.getItem('yxtUser'));
  let count = files.length;
  let failFileSend = [];
  let d1 = $.Deferred(); // 文本发送
  let d2 = $.Deferred(); // 文件发送
  let dd = $.Deferred(); // 总信息传出
  // 发送文本
  if (content) {
    Api.post('/BasePlate/Interface/IInterfaceJson.asmx/Message_SendBatch', {
      User_ID,
      SessionID,
      Unit_ID,
      UserName,
      ReceiveUserIDs: ids.join(','),
      ReceiveUserNames: names.join(','),
      Content: content
    }).then(resp => {
      if(resp.Goodo && resp.Goodo.EID == 0) {
        d1.resolve(`文本发送成功`);
      } else {
        d1.resolve(`文本发送失败`);
      }
    })
  } else {
    d1.resolve(false);
  }
  // 发送文件
  if (count) {
    files.forEach(item => {
      window.fileArr.forEach(iitem => {
        if (iitem.fileName == item) {
          Api.uploadFile(`/BasePlate/Interface/IInterfaceJson.asmx/Message_SendBatchFile`, {
            User_ID, SessionID, UserName, Unit_ID, ReceiveUserIDs: ids.join(','), ReceiveUserNames: names.join(','),
            MsgType: iitem.type, FileName: iitem.fileName, Base64Data: iitem.base64
          }, up, down).then(resp => {
            if (resp.Goodo.EID == '0') {

            } else {
              failFileSend.push(item.fileName);
            }
            count--;
          })
        }
      })
    });

    let check = function() {
      if (count) {
        setTimeout(check, 500);
      } else {
        d2.resolve(`文件发送完毕 --- 失败:${failFileSend.length && failFileSend.join(', ')}`)
      }
    }
    check();
  } else {
    d2.resolve(false)
  }

  $.when(d1, d2).done(function (v1, v2) {
    let output = [];
    v1 && output.push(v1);
    v2 && output.push(v2);
    dd.resolve(output);
  });

  return dd;
}
